package goutil

import (
	"fmt"
	"io"
	"os"
	"time"

	"github.com/lestrrat-go/file-rotatelogs"
)

// path:      日志路径. 空串: 不写入文件
// prefix:    日志文件前缀
//            文件路径格式: path/<prefix_>yyMMdd_hhmm.log
// rotation:  日志分割时间.
// expiry:    日志保留时间.
//            rotation/expiry .e.g:   0: 不设置
//                                    time.Hour*24: 一天
func NewRotateFileWriter(path, prefix string,
	rotation, expiry time.Duration) io.Writer {
	if path == "" {
		return nil
	}
	options := make([]rotatelogs.Option, 0, 3)
	// softLinkName := "last"
	if prefix != "" {
		// softLinkName = prefix
		prefix += "_"
	}
	// options = append(options, rotatelogs.WithLinkName(softLinkName+".log"))
	if rotation > 0 {
		options = append(options, rotatelogs.WithRotationTime(rotation))
	}
	if expiry > 0 {
		options = append(options, rotatelogs.WithMaxAge(expiry))
	}
	fileWriter, err := rotatelogs.New(
		path+string(os.PathSeparator)+prefix+"%y%m%d_%H%M.log", options...)
	if err != nil {
		panic(fmt.Errorf("Rotate log file path: %s, init failed: %s", path, err))
	}
	return fileWriter
}
